Module# 12: Java IO Streams and File                                                               Lecture#45: File IO

 

//   Example 45.1: Knowing information about a File object

 

import java.io.File    

class FileTest  {

      public static void main (String args [ ] ) throws IOException {

            File  fileToCheck;

      if (args.length > 0 ) {

         for (int i = 0; i < args.length;i++ ) {

                  fileToCheck = new File(args[ i ]);

                  getPaths(fileToCheck);

                  getInfo(fileToCheck);

                 }  

      }

      else

               System.out.println (" Usage : Java FileTest <filename (s) >);  

    }

 

     public static void getPaths (File f ) throws IOException {

      System.out.println ("Name : " + f. getName( ) );

      System.out.println ("Path : " + f. getPath ( ) );

      System.out.println ("Parent : " + f.getParent ( ) );

     }

 

     public static void getInfo (File f ) throws IOException  {

      if (f.exists ) {

                  System.out.print ("File exists ");

                  System.out.println (f.canRead( ) ? "and is readable" : "");

                  System.out.println ( f.canWrite( ) ? "and is writable" : "");

                  System.out.println ("File is last modified : + f.lastModified( ));

                  System.out.println ("File is " + f.length( ) + "bytes" );

      }

      else

                  System.err.println (" File does not exist." );

      }

}

 

 

//  Example 45.2: Storing and reading data in the same file

 

import java.io.*;

class ReadWriteIntegers{ 

        public static void main (String args[]) {

            DatalnputStream dis = null;    //Input stream

            DataOutputStream dos = null;   //Output stream

  

            File intFile = new File("rand.dat");        

     

              //Construct a file

      //Writing integers to rand.dat file

      try {    //Create output stream for intFile file

           dos = new DataOutputStream(new FileOutputStream(intFile));

           for(int i=0;i<20;i++)

                  dos.writelnt ((int)(Math. random () *100));

      }

      catch(IOException ioe)     {

            System.out.println(ioe.getMessage());

      }

      finally  {      

            dos.close()

          }      

     }

 

     //Reading integers from rand.dat file

     try {

       //Create input stream for intFile file

              dis = new DatalnputStream(new   FilelnputStream(intFile));   

                

       for(int i=0;i<20;i++) {

            int n = dis.readlnt();

            System.out.print(n + " "); }  

       }

       catch(IOException ioe) {

           System.out.println(ioe.getMessage());

        }

        finally {

             dis.close();

       }   

    }

 }

 

//  Example 45.3: Concatenation and buffering

 

import java.io.*;

class MergeFilesDemo {

       public static void main (String args[]) throws   IOException {

      //Declare file streams

      FilelnputStream file1 = null;

      FilelnputStream file2 = null;     

      SequencelnputStream file3 = null; 

 

      //Declare file3 to store combined files

      file1 = new FilelnputStream("text1.dat");   //Open the files to be concatenated

      file2 = new FilelnputStream("text2.dat");   //Open the files to be concatenated

      file3 = new SequencelnputStream(filel,file2) ;   //Concatenate filel and file2

     

//Create buffered input and output streams

BufferedlnputStream inBuffer = new   BufferedlnputStream(file3);

BufferedOutputStream outBuffer = new   BufferedOutputStream(System.out);

 

//Read and write till the end of buffers

      int ch;

      while((ch = inBuffer.read()) != -1)     

        outBuffer.write((char)ch);

 

inBuffer.close();

outBuffer.close();

file1.close();

file2.close();

     }

}

 

 

//  Example 45.4: Interactive input and output

 

import java. util. *; // To use StringTokenizer class

import java.io.*;

 

class Inventory {

       static DataInputStream din = new DataInputStream(System.in);

       static StringTokenizer st;

       public static void main (String args[J) throws IOException{

DataOutputStream dos = new DataOutputStream(new FileOutputStream("invent.dat"));

     

// Reading from console

      System.out.println("Enter code number");

      st = new StringTokenizer(din.readLine());

      int code = Integer.parseInt(st.nextToken());

 

      System.out.println("Enter number of items");

      st = new StringTokenizer(din.readLine());

      int items = Integer.parselnt(st.nextToken());

 

      System.out.println("Enter cost");

      st = new StringTokenizer(din.readLine());

      double cost = new Double(st.nextToken()).doubleValue{};

 

      // Writing to the file "invent.dat"

      dos.writeInt(code);

      dos.writeInt(items);

      dos.writeDouble(cost);

      dos.close();

 

      // Processing data from the file

       dis = new DataInputStream(new FileInputStream("invent.dat"));

      int codeNumber = dis.readInt();

      int totalItems = dis.readInt();

      double itemCost = dis.readDouble();

   

double totalCost = total Items * itemCost;

      dis.close();

 

      // Writing to console

      System.out.println();

      System.out.println("Code Number : " + codeNumber);

      System.out.println("Item Cost : " + itemCost);

      System.out.println("Total Items : " + totalItems); 

      System.out.println("Total Cost  : " + totalCost);

      }

}

 

//  Example 45.5: Graphical input and output

 

import java.io.*;

import java.awt.*;

 

class StudentFile extends Frame {

    // Defining window components

    TextField number, name, marks;

    Button enter, done;

    Label numLabel, nameLabel, markLabel;

    DataOutputStream dos;

   

    // Initialize the Frame

    public StudentFile(){

        super("Create Student File");

    }

    // Setup the window

    public void setup() {

        resize(400, 200);

        setLayout(new GridLayout(4,2));

 

    // Create the components of the Frame

    number = new TextField(25);

    number = new TextField(25);

    numLabel = new Label("Roll Number");

    name = new TextField(25);

    nameLabel = new Label ("Student Name");

    marks = new TextField(25);

    markLabel = new Label("Marks");

    enter = new Button("ENTER");

    done = new Button("DONE");

    // Add the components to the Frame

    add(numLabel);

    add(number);

    add(nameLabel);

    add(name);

    add(markLabel);

    add(marks);

    add(enter);

    add(done);       

    // Show the Frame

    show();

 

// Open the file

    try    {

    dos new DataOutputStream( new     FileOutputStream("student.dat"));

    }

    catch(IOException e)     {        

        System.err.println(e.toString());

         System.exit(1);

    }

  }

 

  // Write to the file

  public void addRecord()    {

      int num;

      Double d;

      num = (new Integer(number.getText())).intValue();

      try {

        dos.writelnt(num);

        dos.writeUTF(name.getText());

       d = new Double(marks.getText());

       dos.writeDouble(d.doubleValue());

            }

      catch(IOException e) { }

            // Clear the text fields

           number.setText(" ");

           name.setText(" ");

                  marks.setText(" ");

      }

 

     // Adding the record and clearing the TextFields

    public void cleanup()    {

        if(!number.getText(). equals(" ")) {

             addRecord();

        }

        try {

             dos.flush();

             dos.close();

        }

        catch(IOException e) { }

    }

 

// Processing the event

public boolean action(Event event,Object o) {

      if(event.target instanceof Button)

            if(event.arg.equals("ENTER")) {

                        addRecord();

                        return true;

                        }

      return super.action(event, o);

}

 

public boolean handleEvent(Event event) {

      if(event.target instanceof Button)                               

if(event.arg.equals("DONE")) {

                        cleanup();                       

                              System.exit(0);

                        return true;

            }

      return super.handleEvent(event);

  }   

 

     // Execute the program

    public static void main (String args[]) {

      StudentFile student = new StudentFile();

            student.setup();

    }

}